<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import {
  Pod,
  ContainerState,
  Container,
  ContainerStatus
} from "@/views/domain/kubeHud/api/k8s/types";
import { useRoute } from "vue-router";
import { useK8SApi } from "@/views/domain/kubeHud/api/k8s/k8s";
import KDescGroup from "../components/KDescGroup.vue";
import KDescRow from "../components/KDescRow.vue";
import InTagLine from "../components/InTagLine.vue";
import PodTolerations from "./widgets/PodTolerations.vue";
import PodConditions from "./widgets/PodConditions.vue";
import PodContainerStatusCard from "./widgets/PodContainerStatusCard.vue";
import PodVolumeList from "./widgets/PodVolumeList.vue";
import {
  IconCode,
  IconTerminal,
  IconLog
} from "@/views/domain/kubeHud/views/k8s/components/icons";
import { timeTrans } from "../../../utils";
import YamlDialog from "../components/YamlDialog.vue";
import PodLogDialog from "./widgets/PodLogDialog.vue";
import PodTerminalDialog from "./widgets/PodTerminalDialog.vue";

type Prop = {
  name?: string;
  namespace?: string;
};

const props = defineProps<Prop>();
const route = useRoute();
const { podRepo } = useK8SApi();
const loading = ref(false);
const podDetails = ref<Pod>();

const getPodDetails = async (name?: string, namespace?: string) => {
  loading.value = true;

  const { ok, data } = await podRepo.getPodDetail({ name, namespace });
  if (ok) {
    setupContainerState();
  }

  loading.value = false;
};

const setupContainerState = () => {
  const wrapper: { [key: string]: ContainerWrapper } = {};
  podDetails.value.spec.containers.forEach(container => {
    wrapper[container.name] = {
      container: container
    };
  });

  podDetails.value.status.containerStatuses.forEach(status => {
    wrapper[status.name].state = status;
  });

  containerStateWrapper.value = Object.values(wrapper);
};

const reloadPodDetails = async () => {
  if (props.name && props.namespace) {
    getPodDetails(props.name, props.namespace);
  } else if (route.query?.name && route.query?.namespace) {
    getPodDetails(route.query.name as string, route.query.namespace as string);
  } else {
    console.error("No pod name or namespace provided");
  }
};

const runningType = computed(() => {
  switch (podDetails.value?.status.phase) {
    case "Running":
      return "success";
    case "Pending":
      return "warning";
    case "Succeeded":
      return "success";
    case "Failed":
      return "danger";
    case "Unknown":
      return "danger";
    default:
      return "info";
  }
});

type ContainerWrapper = {
  state?: ContainerStatus;
  container?: Container;
};

const containerStateWrapper = ref<ContainerWrapper[]>([]);

onMounted(() => {
  reloadPodDetails();
});
</script>

<template>
  <div v-if="podDetails" class="node-details-wrapper">
    <el-affix :offset="80" target=".node-details-wrapper">
      <div class="node-details-header">
        <span class="node-details-title">
          {{ `Pod: ${podDetails.metadata.name}` }}
        </span>
        <el-button-group>
          <el-button type="primary" icon="Refresh" @click="reloadPodDetails" />
          <YamlDialog :value="podDetails" />
          <YamlDialog :value="podDetails" icon="Edit" edit />
          <PodTerminalDialog
            type="primary"
            :icon="IconTerminal"
            :namespace="podDetails.metadata.namespace"
            :pod-name="podDetails.metadata.name"
            :containers="podDetails.spec.containers"
          />
          <PodLogDialog
            type="primary"
            :icon="IconLog"
            :namespace="podDetails.metadata.namespace"
            :pod-name="podDetails.metadata.name"
            :containers="podDetails.spec.containers"
          />
        </el-button-group>
      </div>
    </el-affix>
    <KDescGroup>
      <KDescRow label="名称" :content="podDetails.metadata.name" />
      <KDescRow label="命名空间" :content="podDetails.metadata.namespace" />
      <KDescRow
        label="创建时间"
        :content="timeTrans(podDetails.metadata.creationTimestamp)"
      />
      <KDescRow label="状态" :content="podDetails.status.phase">
        <el-tag :type="runningType">{{ podDetails.status.phase }}</el-tag>
      </KDescRow>
      <KDescRow label="节点名称" :content="podDetails.spec.nodeName" />
      <KDescRow label="标签">
        <el-space wrap>
          <in-tag-line
            v-for="(value, key) in podDetails.metadata.labels"
            :key="key"
            :title="key"
            :content="value"
          />
        </el-space>
      </KDescRow>
      <KDescRow label="Pod IP" :content="podDetails.status?.podIP" />
      <KDescRow label="Host IP" :content="podDetails.status?.hostIP" />
      <KDescRow
        label="Service Account"
        :content="podDetails.spec?.serviceAccount"
      />
      <KDescRow label="ControlBy">
        <el-space wrap>
          <in-tag-line
            v-for="owner in podDetails.metadata?.ownerReferences"
            :key="owner.uid"
            :title="owner.kind"
            :content="owner.name"
          />
        </el-space>
      </KDescRow>
      <KDescRow label="QoS Class" :content="podDetails.status?.qosClass" />
    </KDescGroup>

    <KDescGroup title="Tolerations">
      <pod-tolerations :tolerations="podDetails.spec?.tolerations" />
    </KDescGroup>

    <KDescGroup title="Conditions">
      <PodConditions :conditions="podDetails.status?.conditions" />
    </KDescGroup>

    <KDescGroup title="Containers">
      <PodContainerStatusCard
        v-for="state in containerStateWrapper"
        :key="state.container?.name"
        :c-state="state.state"
        :container="state.container"
      />
    </KDescGroup>
    <KDescGroup title="Volumes" :border="false">
      <PodVolumeList :volumes="podDetails.spec?.volumes" />
    </KDescGroup>
  </div>
  <div v-else v-loading="true" />
</template>
<style lang="scss">
.node-details-wrapper {
  background-color: var(--el-bg-color);
}

.node-details-header {
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
  background-color: var(--el-bg-color);
}

.node-details-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}
</style>
